

#define UserDefault [NSUserDefaults standardUserDefaults]

#import "LoginViewController.h"

#import "Utils.h"

//#import "nameOfHead.h"
#import "SYVerifyLoginViewController.h"


@interface LoginViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *verLoginButton;
@property (weak, nonatomic) IBOutlet UIView *passwordBackground;
@property (weak, nonatomic) IBOutlet UIView *acountBackground;


@property (weak, nonatomic) IBOutlet UISwitch *useIpSwitch;

- (IBAction)forgetPassword:(id)sender;
- (IBAction)doLogin:(id)sender;
- (IBAction)useIpAction:(id)sender;

@end

@implementation LoginViewController{
    
    BOOL needChangeRootViewController;
}

@synthesize usernameTextField = _usernameTextField;
@synthesize passwordTextField = _passwordTextField;
@synthesize loginButton = _loginButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        
    }
    return self;
}
- (void)viewSetCornerRadius:(UIView *)view{
    view.layer.cornerRadius = 6.0f;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.IdArray=[[NSMutableArray alloc]init];
    self.contactsSource=[NSMutableArray array];
    [self viewSetCornerRadius:_loginButton];
    
    //[self viewSetCornerRadius:_passwordBackground];
    //[self viewSetCornerRadius:_acountBackground];
    
    self.nameDic=[NSDictionary dictionary];
    
    //[self setupForDismissKeyboard];
    _usernameTextField.delegate = self;
    //_usernameTextField.placeholder = @"师云号/手机号";
    NSMutableAttributedString *placeholder1 = [[NSMutableAttributedString alloc]initWithString:@"师云号/手机号"];
    [placeholder1 addAttribute:NSForegroundColorAttributeName
                        value:colorFromHex(@"#d2d2d2")
                        range:NSMakeRange(0, 7)];
    _usernameTextField.attributedPlaceholder = placeholder1;
    
    
    _passwordTextField.delegate = self;
    _passwordTextField.tintColor = [UIColor blueColor]; //设置光标的颜色
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:@"密码"];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:colorFromHex(@"#d2d2d2")
                       range:NSMakeRange(0, 2)];
    _passwordTextField.attributedPlaceholder = placeholder;
    
    [_loginButton setBackgroundColor:colorFromHex(@"#b4e0ff")];
    _verLoginButton.layer.borderColor = [DEFAULTCOLOR CGColor];
    [_verLoginButton setTitleColor:DEFAULTCOLOR forState:(UIControlStateNormal)];
    
//    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 171, SCREENWIDTH, 0.5)];
//    [lineView setBackgroundColor:colorFromHex(@"#DEDEDE")];
//    [self.view addSubview:lineView];
    
    //添加内容改变的监听
    [_passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    NSString *username = [self lastLoginUsername];
    if (username && username.length > 0) {
        _usernameTextField.text = username;
    }
    
    self.navBar.nav_titleLabel.text = @"登录";
    
    _usernameTextField.delegate=self;
    [_usernameTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
    if ([ud objectForKey:@"sound"]==nil||[ud objectForKey:@"zhendong"]==nil) {
        [ud setObject:@"no" forKey:@"noMessage"];
        [ud setObject:@"yes" forKey:@"sound"];
        [ud setObject:@"yes" forKey:@"zhendong"];
        [ud synchronize];
    }
    
    NSDictionary *dic;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doLogin:) name:@"SY_verifyDoLogin" object:dic];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerScuess:) name:@"registerScuess" object:nil];
}


-(void)registerScuess:(NSNotification *)noti{
    
    NSDictionary *dic = noti.object;
    
    NSString *loginName = [dic objectForKey:@"phone"];
    
    NSString *loginPass = [dic objectForKey:@"password"];
    
    self.usernameTextField.text = loginName;
    self.passwordTextField.text = loginPass;
    
    
    self.loginButton.enabled = YES;
    self.loginButton.backgroundColor = DEFAULTCOLOR;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//注册账号
- (IBAction)doRegister:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController * view = [storyboard instantiateViewControllerWithIdentifier:@"RegisteViewController"];
    [self.navigationController pushViewController:view animated:YES];
    
}

- (void)loginWithUsername:(NSString *)username password:(NSString *)password {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
    
    [self saveLastLoginUsername];
    
    
}


#pragma mark -忘记密码
- (IBAction)forgetPassword:(id)sender {
    
    SYVerifyLoginViewController *verifyVC = [[SYVerifyLoginViewController alloc] initWithNibName:@"SYVerifyLoginViewController" bundle:nil];
    [self.navigationController pushViewController:verifyVC animated:YES];
    
    
}

#pragma mark -登录点击事件
- (IBAction)doLogin:(id)sender {
    
    if ([sender isKindOfClass:[NSNotification class]]) {
        NSLog(@"%@",sender);
        
        NSDictionary *dic = [sender valueForKeyPath:@"object"];
        
        self.usernameTextField.text = [dic objectForKey:@"_phoneNum"];
        self.passwordTextField.text = [dic objectForKey:@"newpass"];
    }
    
    if (![self isEmpty]) {
        [self.view endEditing:YES];
        
        NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
        [dict setObject:@"api_user_login" forKey:@"method"];
        [dict setObject:self.usernameTextField.text forKey:@"loginname"];
        
        NSString * finalPassWord = [Utils MD5EncryptWith:self.passwordTextField.text];
        [dict setObject:finalPassWord forKey:@"userpass"];
        
        [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
            
            NSLog(@"---%@--LOGIN",resposeJson);
            NSDictionary * dict = (NSDictionary *)resposeJson;
            NSDictionary *redataDic=[dict objectForKey:@"re_data"];
            NSDictionary *dbDic=[[dict objectForKey:@"re_data"] objectForKey:@"userinfo"];
            [UserDefault setObject:[dbDic objectForKey:@"userid"] forKey:@"userid"];
            [UserDefault synchronize];
            
            //判断是否开通平安家校
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setObject:USERID forKey:@"userid"];
            [Utils Java_get:@"api/isOpenFace" parameters:param success:^(NSInteger recode, id jsonObject) {
                
                NSDictionary *jsonDict = (NSDictionary *)jsonObject;
                NSDictionary *re_data=[jsonDict objectForKey:@"re_data"];
                
                if ([[re_data objectForKey:@"openface"] integerValue] == 1) {
                    
                    int firstlogin = [[redataDic objectForKey:@"firstlogin"] intValue];
                    /*如果是首次登陆的话，需要存到userdefaults里面,在mainViewController里用*/
                    //firstlogin = 1;
                    if (firstlogin == 1) {
                        
                        [[NSUserDefaults standardUserDefaults] setInteger:firstlogin forKey:SYISFirstLogin];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                    }
                    
                    NSMutableDictionary *personalImformation = [[NSMutableDictionary alloc]initWithDictionary: [dict objectForKey:@"re_data"]];
                    if (personalImformation.count>0) {
                        
                        [personalImformation setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                        [personalImformation setObject:[NSString stringWithFormat:@"%@",[re_data objectForKey:@"facetype"]] forKey:@"facetype"];
                       
                        NSMutableDictionary * userinfo = [[NSMutableDictionary alloc]initWithDictionary: [personalImformation objectForKey:@"userinfo"]];
                        [userinfo setObject:[NSString stringWithFormat:@"%d",[[re_data objectForKey:@"faceuserid"] intValue]] forKey:@"faceuserid"];
                        [userinfo setObject:[NSString stringWithFormat:@"%@",[re_data objectForKey:@"facetype"]] forKey:@"facetype"];
                       
                        [personalImformation setObject:userinfo forKey:@"userinfo"];
                        
                        NSInteger lastTypeNum = [[userinfo objectForKey:@"lasttype"] integerValue];

                        if (lastTypeNum == 0) {
                            
                            int haveclass = [[personalImformation objectForKey:@"haveclass"] intValue];
                            int havestudent = [[personalImformation objectForKey:@"havestudent"] intValue];
                            int schoolNum = [[userinfo objectForKey:@"schoolnum"] intValue];
                            
                            if (schoolNum > 0 && havestudent == 0 && haveclass == 0) {
                                [personalImformation setObject:@"1" forKey:@"lasttype"];
                            }
                        }
                        
                        if ([userinfo objectForKey:@"userid"] != nil) {
                            [self saveStudentID:[userinfo objectForKey:@"userid"]];
                        }
                        
                        
                        AppDelegate * delegate = (AppDelegate *)CONSTAPPDELEGATE;
                        delegate.isChangeRole=@"yes";
                        
                        
                        //存入scid
                        NSString *scid = [[re_data objectForKey:@"scid"] stringValue];
                        [personalImformation setObject:scid forKey:@"scid"];
                        
                        [self saveUserDataWithResposeData:personalImformation];
                    }
                    
                    /*从新登录，清理webview缓存*/
                    [Utils clearWebViewCache];
                    
                    //再次绑定chinnelid
                    AppDelegate *delegate =(AppDelegate *)[UIApplication sharedApplication].delegate;
                    
                    [delegate bindChinnelId];
                    
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此账号未开通平安家校" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil,nil];
                    
                    [alert show];
                }
                
                
            }failure:^(NSInteger recode, NSError *error) {
                
            }];

        } failure:^(NSInteger recode, NSError * error){
            
            [self showHint:error.localizedDescription];
        }];
    }
}
-(void)saveStudentID:(NSString *)userid
{
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_parentstudent_list" forKey:@"method"];
    [dict setObject:@"20" forKey:@"pagesize"];
    [dict setObject:userid forKey:@"parentid"];
    [dict setObject:@"1" forKey:@"pageno"];
    [Utils get:nil parameters:dict success:^(NSInteger recode, id resposeJson){
        NSDictionary * dict = (NSDictionary *)resposeJson;
        if ([[dict objectForKey:@"re_code"] integerValue]==0) {
            if ([[dict objectForKey:@"re_data"] count]>0) {
                NSUserDefaults *ud=[NSUserDefaults standardUserDefaults];
                [ud setObject:[[[dict objectForKey:@"re_data"] objectAtIndex:0]objectForKey:@"userid"] forKey:@"studentID"];
                [ud synchronize];
            }
        }
        
    } failure:^(NSInteger recode, NSError * error){
        
    }];
    
}


//保存用户数据
- (void)saveUserDataWithResposeData:(NSMutableDictionary *)personalImformation
{
    
    BOOL save = [SyUserInfomation personalImformationSaveWtih:personalImformation];
    NSLog(@"save status 1 is success 0 is failture :%i",save);
    NSDictionary * userinfo = [personalImformation objectForKey:@"userinfo"];
    NSString * userID = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"userid"]];
    NSString * userPass = [NSString stringWithFormat:@"%@",[userinfo objectForKey:@"loginpass"]];
    
    //手机号 mobile
    NSString *mobile = [userinfo objectForKey:@"mobile"];
    //头像 logo
    NSString *logo = [userinfo objectForKey:@"logo"];
    //上一次登录身份
    NSString *lastType = [[userinfo objectForKey:@"lasttype"] stringValue];
    
    NSUserDefaults * UD = [NSUserDefaults standardUserDefaults];
    [UD setObject:mobile forKey:@"mobile"]; //手机号
    [UD setObject:userID forKey:@"userid"]; //userid
    [UD setObject:logo forKey:XZHEADURL];
    [UD setObject:@"1" forKey:@"isLogin"];
    //＊＊＊＊＊＊＊Add by zz（16.05.04）［存储了上一次的登录状态］＊＊＊＊＊＊＊＊＊＊
    [UD setObject:lastType forKey:XZLASTTYPE];
    //＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊End＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊
    [UD synchronize];
    //＊＊＊＊＊＊＊Add by zz（16.05.04）［存储了上一次的登录状态］＊＊＊＊＊＊＊＊＊＊
    
    //＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊End＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊

    
    [self loginWithUsername:userID password:userPass];
    
}

- (BOOL)isEmpty{
    BOOL ret = NO;
    NSString *username = _usernameTextField.text;
    NSString *password = _passwordTextField.text;
    if (username.length == 0 || password.length == 0) {
        ret = YES;
//        [EMAlertView showAlertWithTitle:NSLocalizedString(@"prompt", @"Prompt")
//                                message:NSLocalizedString(@"login.inputNameAndPswd", @"Please enter username and password")
//                        completionBlock:nil
//                      cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
//                      otherButtonTitles:nil];
    }
    
    return ret;
}


#pragma  mark - TextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField == _usernameTextField) {
        _passwordTextField.text = @"";
        _loginButton.enabled = NO;
        [_loginButton setBackgroundColor:DEFAULTCOLOR];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _usernameTextField) {
        [_usernameTextField resignFirstResponder];
        [_passwordTextField becomeFirstResponder];
    } else if (textField == _passwordTextField) {
        [_passwordTextField resignFirstResponder];
        [self doLogin:nil];
    }
    return YES;
}


#pragma  mark - private
- (void)saveLastLoginUsername
{
    
    NSString *username=_usernameTextField.text;
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
        [ud setObject:self.nameDic forKey:@"user_names"];
        [ud synchronize];
    }
    
}

- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
    if (username && username.length > 0) {
        return username;
    }
    
    return nil;
}



#pragma mark - private
- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == _usernameTextField) {
        if (textField.text.length > 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    
    
    if (textField==_passwordTextField)
    {
        if (_passwordTextField.text.length > 16) {
            UITextRange *markedRange = [_passwordTextField markedTextRange];
            if (markedRange) {
                return;
            }
            //Emoji占2个字符，如果是超出了半个Emoji，用15位置来截取会出现Emoji截为2半
            //超出最大长度的那个字符序列(Emoji算一个字符序列)的range
            NSRange range = [_passwordTextField.text rangeOfComposedCharacterSequenceAtIndex:16];
            _passwordTextField.text = [_passwordTextField.text substringToIndex:range.location];
        }
        
    }

    
    if (_usernameTextField.text.length > 0 && _passwordTextField.text.length >= 6 && _passwordTextField.text.length<=16) {
        
        _loginButton.enabled = YES;
        [_loginButton setBackgroundColor:DEFAULTCOLOR];
        
    }else{
        
        _loginButton.enabled = NO;
        [_loginButton setBackgroundColor:colorFromHex(@"#b4e0ff")];
    }
}

@end
